<template>
  <div>
    <div id="mapContainer"
         :style="{width: detail.style.position.w + 'px',height: detail.style.position.h + 'px'}"></div>
    <div class="info_window">
      <el-select v-model="deviceMac" filterable placeholder="请选择" @change="handleChange">
        <el-option
            v-for="item in deviceData"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
    </div>
  </div>

</template>

<script>
import BaseView from './View';
import offLineImg from '@/views/zutai/images/offLine.png'
import onLineImg from '@/views/zutai/images/onLine.png'
import warnLineImg from '@/views/zutai/images/warnLine.png'
import request from '@/utils/request';

export default {
  name: 'view-map',
  extends: BaseView,
  components: {},
  data() {
    return {
      onLineImg: onLineImg,
      warnLineImg: warnLineImg,
      offLineImg: offLineImg,
      timer: null,
      center: {},
      deviceMac: '',
      deviceData: [],
      mapType: '',
      points: [],
      zoom: 15,
      map: null,
    };
  },
  computed: {
    mapStyleChange() {
      return this.detail.style.mapType + '-' + this.detail.style.mapModel;
    }
  },
  watch: {
    mapStyleChange() {
      this.initMap();
    },
  },
  mounted() {
    this.getList('init');
    this.timer = setInterval(this.getList, 60000 * 10);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    handleChange() {
      this.getList();
    },
    getList(label) {
      let url = "/zutai/bDeviceManager/list"
      let param = {
        pageNum: 1,
        pageSize: 9999,
        deviceMac: this.deviceMac
      }
      request({
        url: url,
        method: "get",
        params: param,

      }).then((res) => {
        this.points = res.rows
        if (this.points.length > 0) {
          this.center.lng = this.points[0].longitude;
          this.center.lat = this.points[0].latitude;
        }
        this.initMap();
        if (label == 'init') {
          this.deviceData = [{
            label: '全部',
            value: ''
          }]
          res.rows.forEach(element => {
            let data = {
              label: element.deviceName,
              value: element.deviceMac
            }
            this.deviceData.push(data)
          });
        }
      })
    },
    initMap() {
      console.log('地图开始初始化');
      var map = new BMapGL.Map("mapContainer", {
        enableMapClick: false
      }); // 创建Map实例
      map.centerAndZoom(new BMapGL.Point(this.center.lng, this.center.lat), this.zoom); // 初始化地图,设置中心点坐标和地图级别
      map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
      if (this.detail.style.mapType == '地球模式') {
        map.setMapType(BMAP_SATELLITE_MAP);
      } else {
        map.setMapType(BMAP_NORMAL_MAP);
      }
      this.map = map;
      this.map.setMapStyleV2({
        styleId: this.detail.style.mapModel
      });
      let data = [];
      this.points.forEach(element => {
        data.push({
          geometry: {
            type: "Point",
            detail: element,
            coordinates: [
              element.longitude, element.latitude
            ]
          },
          properties: {
            icon: [offLineImg, onLineImg, warnLineImg][element.deviceStatus],
            deviceId: element.id,
            width: 20,
            height: 20
          }
        });
      });
      var view = new mapvgl.View({
        map: map
      });
      let that = this;
      var clusterLayer = new mapvgl.ClusterLayer({
        size: 20,
        minSize: 30, // 聚合点显示的最小直径
        maxSize: 50, // 聚合点显示的最大直径
        clusterRadius: 150, // 聚合范围半径
        gradient: {0: 'blue', 0.5: 'green', 1.0: 'red'}, // 聚合点颜色梯度
        maxZoom: 15, // 聚合的最大级别，当地图放大级别高于此值将不再聚合
        minZoom: 5, // 聚合的最小级别，当地图放大级别低于此值将不再聚合
        // 是否显示文字
        showText: true,
        // 开始聚合的最少点数，点数多于此值才会被聚合
        minPoints: 20,
        // 设置文字样式
        textOptions: {
          fontSize: 12,
          color: 'white',
          // 格式化数字显示
          format: function (count) {
            return count >= 10000 ? Math.round(count / 1000) + 'k'
                : count >= 1000 ? Math.round(count / 100) / 10 + 'k' : count;
          }
        },
        enablePicked: true,
        onClick(e) {
          if (e) {
            // 可通过dataItem下面的children属性拿到被聚合的所有点
            console.log(e.dataItem);
            if (e.dataItem == undefined) {
              console.log('点击空白处');
              return;
            }
            if (e.dataItem.children == undefined) {
              var anchor = e.dataItem;
              var deviceId = anchor.properties.deviceId;
              request({
                url: "/zutai/bDeviceManager/" + deviceId,
                method: "get",
              }).then(res => {
                let deviceDetail = res.data
                // 在此处编写弹窗的自定义HTML内容和样式
                let deviceStatus = ''
                if (deviceDetail.deviceStatus == 1) {
                  deviceStatus = `设备状态：<span style="color:#67C23A">在线</span>`
                } else if (deviceDetail.deviceStatus == 2) {
                  deviceStatus = `设备状态：<span style="color:#F56C6C">报警</span>`
                } else {
                  deviceStatus = `设备状态：<span style="color:#909399">离线</span>`
                }
                var infoWindowContent = `<div>` +
                    `<p>设备编号：` + deviceDetail.deviceMac + `</p>` +
                    `<p>设备名称：` + deviceDetail.deviceName + `</p>` +
                    `<p>设备地址：` + deviceDetail.installationAddress + `</p>` +
                    `<p>经纬度：` + deviceDetail.longitude + ',' + deviceDetail.latitude + `</p>` +
                    deviceStatus +
                    `</div>`;

                // 创建信息窗口并设置位置
                var infoWindow = new BMapGL.InfoWindow(infoWindowContent, {
                  width: 280,
                  height: 200,
                  enableCloseOnClick: true
                });
                var point = new BMapGL.Point(anchor.geometry.coordinates[0], anchor.geometry.coordinates[1]);
                // 在点击锚点的位置打开信息窗口
                map.openInfoWindow(infoWindow, point);
              });

            } else {
              console.log('锚点点击');
            }
          }
        }
      });

      view.addLayer(clusterLayer);
      clusterLayer.setData(data);
      console.log('渲染地图个数', data.length);
    },
  }
};
</script>
<style scoped>
.info_window {
  background-color: #FAF9F7;
  opacity: 0.8;
  position: absolute;
  top: 10px;
  left: 10px;
  border-radius: 1%;
  box-shadow: 0 0 10px 0 #FAF9F7;
  z-index: 99999;
}
</style>
<style>
.BMap_cpyCtrl {
  display: none;
}

.anchorBL {
  display: none;
}
</style>
